package org.ktjy.demo.comfig;

import org.ktjy.demo.entity.SysUser;
import org.ktjy.demo.service.ISysRoleRightService;
import org.ktjy.demo.service.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


import javax.annotation.Resource;
import java.util.List;

/*


 */

public class CustoRealn extends AuthorizingRealm {
    @Resource
    ISysUserService sysUserService;



    @Resource
    ISysRoleRightService sysRoleRightService;

    //定义授权域  查询认证的主体可访问的权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        info.addRole(String.valueOf(sysUser.getUsrRoleId()));
        List<String> resources = sysRoleRightService.getRoleByRoleId(sysUser.getUsrRoleId());

        info.addStringPermissions(resources);

        return info;
    }


    //定义认证域
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        SysUser sysUser = sysUserService.getUserByUsrName(username, password);
        if (sysUser != null) {
            throw new UnknownAccountException();
        }
        if (sysUser.getUsrFlag() != 1) {
            throw new LockedAccountException();
        }
//        if () {
//
//        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, sysUser.getUsrPassword(), String.valueOf(sysUser.getUsrId()));
        return info;
    }

}
